﻿/*
 * Copyright 2009, Payton Byrd
 * Licensed Under the Microsoft Public License (MS-PL)
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PaytonByrd.Extensions
{
    /// <summary>
    /// A collection of extension methods
    /// used to perform operations on 
    /// collections.
    /// </summary>
    public static class CollectionExtensions
    {
        /// <summary>
        /// Gets the first item of the List.
        /// </summary>
        /// <typeparam name="T">Type of items
        /// in the list.</typeparam>
        /// <param name="collection">The list containing
        /// the desired item.</param>
        /// <returns>Null if empty, instance of T
        /// if at least one item exists.</returns>
        public static T FirstItem<T>(
            this List<T> collection)
        {
            collection.AssertParameterNotNull(
                "The collection cannot be null.",
                "collection");

            if (collection.IsNotEmpty<T>())
            {
                return collection[0];
            }

            return default(T);
        }

        /// <summary>
        /// Gets the first item of the
        /// array.
        /// </summary>
        /// <param name="array">The array
        /// containing the desired item.</param>
        /// <returns>Null if the array
        /// is empty, the first item if 
        /// available.</returns>
        public static object FirstItem(
            this Array array)
        {
            array.AssertParameterNotNull(
                "The array cannot be null.",
                "array");

            if (array.IsNotEmpty())
            {
                return array.GetValue(0);
            }

            return null;
        }

        /// <summary>
        /// Gets the first <see cref="System.Data.DataRow"/>
        /// (as T) of the DataTable.
        /// </summary>
        /// <typeparam name="T">The type of
        /// DataRow to return.</typeparam>
        /// <param name="table">The DataTable containing
        /// the desired row.</param>
        /// <returns>Null if the DataTable is empty,
        /// instance of DR if at least one DataRow
        /// exists.</returns>
        public static T FirstRow<T>(
            this System.Data.DataTable table)
            where T : System.Data.DataRow
        {
            if (table.IsNotEmpty<T>())
            {
                return (T)table.Rows[0];
            }

            return (T)null;
        }
    }
}
